import { createWebHistory, createRouter } from "vue-router"
import Dashboard from "../views/Dashboard.vue";
import Login from "../views/Login.vue";
import {useAuth} from "../services/auth.service.js";
import TokenService from "../services/token.service.js";

const routes = [
    {
        path: "/",
        name: "Dashboard",
        component: Dashboard,
        meta: { requiresAuth: true },
    },
    {
        path: "/login",
        name: "Login",
        component: Login,
        meta: { requiresAuth: false },
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes,
});

router.beforeEach((to, from, next) => {

    // check user auth token
    const token = TokenService.getToken()
    if (token) {
        const auth = useAuth()
        auth.setUser(TokenService.getUser(), true)
    }

    const { authenticating, user } = useAuth()

    // Not logged into a guarded route?
    if (!token && to.meta?.requiresAuth === true) {
        console.log('requires auth, redirect to login');
        next({ name: 'Login' })
    }
    else next()
})

export default router;
